package com.base;

import sun.awt.windows.ThemeReader;

/**
 * 根据中断标志类判断线程是否终止
 **/
public class Demo07_DetermineIfTheThreadIsTerminatedByInterruptFlag {

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                // 如果当前线程被中断, 则退出循环
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + " Hello: " + Thread.currentThread().isInterrupted());
                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        // 线程阻塞时调用 interrupt(), 会抛出异常
                        System.out.println("抛出异常后状态:" + Thread.currentThread().isInterrupted());
                        e.printStackTrace();
                        return;
                    }
                }
                System.out.println("threadA is over , " + Thread.currentThread().isInterrupted());
            }
        });
        // 启动子线程
        threadA.start();
        // 主线程休眠 1s, 以便中断前让子线程输出
        System.out.println("main thread sleep");
        Thread.sleep(1);

        // 中断子线程
        System.out.println("main thread interrupt threadA");
        threadA.interrupt();

        // main thread will wait threadA

        threadA.join();
        System.out.println("main thread is over");
    }


}
